<template>
  <div class="pay-wrapper">
    <div class="pay-content">
      <step-group :step-list="stepList"></step-group>
      <count-down
        tips-text="来支付订单，超时订单自动关闭"
        surplus-tips="订单支付已超时"
        :surplus-date="surplusDate"
        class="count-down"
        @timeout="timeout"
      ></count-down>
      <div class="content-wrapper">
        <el-table
          :data="orderlist"
          :header-cell-style="rowClass"
          :cell-style="cellStyle"
          v-if="!loading"
        >
          <el-table-column width="150">
            <template slot-scope="scope">
              <div class="info-img">
                <img
                  class="img"
                  :src="scope.row.orderData.product.product_img.length == 0 ? require('@/assets/hall/default1.jpg'):scope.row.orderData.product.product_img[0]"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品信息">
            <template slot-scope="scope">
              <div class="info-wrapper">
                <span class="text">{{scope.row.orderData.product.product_name}}</span>
                <span
                  v-show="scope.row.orderData.product.product_place"
                >/{{scope.row.orderData.product.product_place}}</span>
                <span
                  v-show="scope.row.orderData.product.product_style"
                >/{{scope.row.orderData.product.product_style}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="每份订金" width="150">
            <template slot-scope="scope">￥{{scope.row.orderData.agent.agent_each_copies_deposit}}</template>
          </el-table-column>
          <el-table-column label="代理份数" width="170">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.orderData.agent.agent_copies"
                :min="start_copies"
                :max="parseFloat(scope.row.orderData.agent.product_surplus)"
                style="width:145px;"
                onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="代理费支付模式" width="150">
            <template
              slot-scope="scope"
            >{{scope.row.orderData.agent.agent_pay_way == 0 || scope.row.orderData.product.payment_mode=='FLEXIBLE' ? '按月支付' : '一次性支付'}}</template>
          </el-table-column>
          <el-table-column label="代理期限" width="150">
            <template slot-scope="scope">
              <span
                v-if="scope.row.orderData.product.payment_mode=='FLEXIBLE'"
              >{{scope.row.orderData.agent.agent_time+'~'+scope.row.orderData.product.agency_stage_max+'个月'}}</span>
              <span v-else>{{scope.row.orderData.agent.agent_time}}个月</span>
            </template>
          </el-table-column>
          <el-table-column label="代理费率" width="150">
            <template
              slot-scope="scope"
            >{{scope.row.orderData.agent.agent_rate ? (scope.row.orderData.agent.agent_rate * 100).toFixed(4) + '%' : '-'}}</template>
          </el-table-column>
          <el-table-column label="订金" width="150">
            <template
              slot-scope="scope"
              width="150"
            >￥{{(scope.row.orderData.agent.agent_each_copies_deposit * scope.row.orderData.agent.agent_copies).toFixed(2)}}</template>
          </el-table-column>
        </el-table>
      </div>
      <div class="operation-wrapper">
        <span>
          已选择
          <span class="count">{{totalCount}}</span>份
        </span>
        <span>
          总价
          <span class="count price">￥{{totalPrice}}</span>
        </span>
        <el-button v-if="readFlag" type="primary" @click="_preCheckAction">去结算并签署合同</el-button>
        <el-button v-else type="primary" class="is-disabled" @click="_doOrder(0)">去结算并签署合同</el-button>
      </div>
      <div class="read-box">
        <el-checkbox v-model="readFlag"></el-checkbox>
        <span>
          我已阅读并同意签署
          <span class="read-span" @click="_openAgentSsq">《代理合同》</span>
        </span>
      </div>

      <el-dialog
        custom-class="pages-dialog"
        :visible.sync="pagesFlag"
        :close-on-click-modal="false"
        :lock-scroll="false"
        :fullscreen="true"
        :show-close="false"
      >
        <span slot="title" class="pages-dialog-title">云木屋</span>
        <div v-if="pagesType==1" class="pages-wrap">
          <div class="pages-img">
            <img src="@/assets/hall/tipsPage1.png" alt />
          </div>
          <div class="pages-text">
            <h2>正在排队...</h2>
            <p>该商品人气火爆，请耐心排队等待</p>
          </div>
          <div class="pages-btn">
            <el-button @click="backDetails">返回商品详情</el-button>
          </div>
        </div>
        <div v-else-if="pagesType==2" class="pages-wrap">
          <div class="pages-img">
            <img src="@/assets/hall/tipsPage2.png" alt />
          </div>
          <div class="pages-text">
            <h2>机会来啦！</h2>
            <p>运气不错哟，正在前往支付...</p>
          </div>
        </div>
        <div v-else-if="pagesType==3" class="pages-wrap">
          <div class="pages-img">
            <img src="@/assets/hall/tipsPage3.png" alt />
          </div>
          <div class="pages-text">
            <h2>可代理份数不足</h2>
            <p>可代理份数不足，请重新代理</p>
          </div>
          <div class="pages-btn pages-btn-bl">
            <el-button @click="backDetails">重新代理</el-button>
          </div>
        </div>
        <div v-else-if="pagesType==4" class="pages-wrap">
          <div class="pages-img">
            <img src="@/assets/hall/tipsPage4.png" alt />
          </div>
          <div class="pages-text">
            <h2>代理已满</h2>
            <p>该代理商品已满，请选择其他商品代理</p>
          </div>
          <div class="pages-btn pages-btn-bl">
            <el-button @click="backagencyList">查看更多代理</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import StepGroup from "@/components/StepGroup/StepGroup";
import CountDown from "@/components/CountDown/CountDown";
import {
  doAgentOrder,
  doOrder,
  preCheckAction,
  openAgentSsq,
} from "@/api/agency";
const steplist = {
  step: 1,
  list: [
    {
      text: "下单",
      icon: require("@/assets/step/1.png"),
      iconCurr: require("@/assets/step/1_curr.png"),
    },
    {
      text: "支付订金",
      icon: require("@/assets/step/2.png"),
      iconCurr: require("@/assets/step/2_curr.png"),
    },
    {
      text: "平台审核",
      icon: require("@/assets/step/3.png"),
      iconCurr: require("@/assets/step/3_curr.png"),
    },
    {
      text: "代理成功",
      icon: require("@/assets/step/4.png"),
      iconCurr: require("@/assets/step/4_curr.png"),
    },
  ],
};

export default {
  name: "pay",
  data() {
    return {
      readFlag: true,
      stepList: steplist,
      surplusDate: new Date().getTime() + 300000,
      orderlist: [],
      loading: true,
      pagesFlag: false,
      pagesType: "",
      jhFlag: false,
      lxNum: 0,
      reqParams: {
        product_id: "",
        copies: "",
        token: "",
      },
      repeatCheck: null,
      payment_mode: "",
    };
  },
  created() {
    if (this.$route.params.id) {
      this.reqParams.product_id = this.$route.params.id;
      this.reqParams.copies = this.$route.params.copies;
      this.reqParams.token = this.$route.params.token;
      this._doAgentOrder();
    } else {
      this.$router.go(-1);
    }
  },
  computed: {
    start_copies() {
      let start = parseFloat(this.orderlist[0].orderData.agent.start_copies);
      let surplus = parseFloat(
        this.orderlist[0].orderData.agent.product_surplus
      );
      let num = start < surplus ? start : surplus;
      return parseFloat(num) || 0;
    },
    totalCount() {
      return this.orderlist.length
        ? this.orderlist[0].orderData.agent.agent_copies
        : 0;
    },
    totalPrice() {
      return this.orderlist.length
        ? (
            this.orderlist[0].orderData.agent.agent_each_copies_deposit *
            this.orderlist[0].orderData.agent.agent_copies
          ).toFixed(2)
        : 0;
    },
  },
  methods: {
    _openAgentSsq() {
      let params = {
        type: this.payment_mode == "FLEXIBLE" ? 3 : 1,
      };
      console.log("是否灵活代理", params);
      openAgentSsq(params).then((res) => {
        if (res.code == 1) {
          window.open(res.data.url);
        }
      });
    },
    _doAgentOrder() {
      this.loading = true;
      doAgentOrder(this.reqParams)
        .then(
          (res) => {
            this.orderlist.push(res.data);
            this.payment_mode = res.data.orderData.product.payment_mode;
            // console.log("商品信息", this.orderlist);
          }
          // res => {
          //   setTimeout(() => {
          //     this.$message("正在为你返回上一页");
          //     this.$router.go(-1);
          //   }, 1000);
          // }
        )
        .finally(() => {
          this.loading = false;
        });
    },
    _doOrder(flag) {
      if (flag) {
        doOrder({
          product_id: this.$route.params.id,
          copies: this.orderlist[0].orderData.agent.agent_copies,
        }).then((res) => {
          if (res.code == 1) {
            window.location.href = res.data.url;
          } else if (res.code == 20210) {
            // 排队
            this._preCheckAction();
          }
        });
      } else {
        this.$message.error("请阅读并同意签署 《代理合同》");
      }
    },
    // 返回商品详情
    backDetails() {
      clearTimeout(this.repeatCheck);
      this.pagesFlag = false;
      this.jhFlag = false;
      this.lxNum = 0;
      this.$router.push({
        name: "agencydetail",
        params: { id: this.$route.params.id },
      });
    },
    // 查看更多代理
    backagencyList() {
      this.pagesFlag = false;
      this.$router.push({
        name: "agency",
      });
    },
    // 循环检测
    _preCheckAction() {
      // 预购买检查接口(有订金);
      preCheckAction({
        product_id: this.$route.params.id,
        copies: this.orderlist[0].orderData.agent.agent_copies,
      }).then((res) => {
        // console.log("预购买检查接口", res);
        // res.code = 20210;
        if (res.code == 1) {
          // 成功，显示机会来了
          if (this.jhFlag) {
            this.pagesFlag = true;
            this.pagesType = 2;
            setTimeout(() => {
              this._doOrder(1);
              this.pagesFlag = false;
              this.jhFlag = false;
            }, 1000);
          } else {
            this._doOrder(1);
          }
        } else if (res.code == 20210) {
          // 排队
          this.pagesFlag = true;
          this.pagesType = 1;
          this.jhFlag = true;
          this.lxNum++;
          if (this.lxNum > 60) {
            // this.$message({
            //   message: "排队时间超时，正在前往商品详情页",
            //   type: "warning"
            // });
            // setTimeout(() => {
            //   this.backDetails();
            // }, 1500);
            this.backDetails();
          } else {
            console.log("排队轮循", this.lxNum);
            this.repeatCheck = setTimeout(() => {
              this._preCheckAction();
            }, 5000);
          }
        } else if (res.code == 20220) {
          // 可代理份数不足
          this.pagesFlag = true;
          this.pagesType = 3;
        } else if (res.code == 20230) {
          // 代理已满
          this.pagesFlag = true;
          this.pagesType = 4;
        }
      });
    },
    timeout() {
      this.$alert("订单已超时", "提示", {
        confirmButtonText: "返回海量货源",
        callback: (action) => {
          this.$router.push({ path: "/agency" });
        },
      });
    },
    rowClass() {
      return "background:rgba(240,249,252,1);font-size:14px;color:#999;font-weight:400;text-align:center;";
    },
    cellStyle() {
      return "height:110px;font-size:14px;color:#333;text-align:center;";
    },
  },
  components: {
    StepGroup,
    CountDown,
  },
};
</script>
<style lang="scss">
.pages-dialog {
  height: 100%;
  overflow: hidden;
  .el-dialog__header {
    padding: 0;
    padding-left: 70px;
    .pages-dialog-title {
      display: inline-block;
      line-height: 60px;
      font-size: 30px;
      font-weight: bold;
      background-image: linear-gradient(0deg, #ff9303 0%, #fe6018 100%);
      -webkit-background-clip: text;
      color: transparent;
    }
  }
  .el-dialog__body {
    text-align: center;

    .pages-wrap {
      margin-top: 100px;
      .pages-img {
        img {
          width: 540px;
          height: 350px;
        }
      }
      .pages-text {
        margin: 50px 0 30px 0;
        h2 {
          font-size: 22px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          color: rgba(17, 17, 17, 1);
        }
        p {
          font-size: 18px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: rgba(153, 153, 153, 1);
        }
      }
      .pages-btn {
        .el-button {
          background: #ff6f47;
          font-size: 18px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: rgba(255, 255, 255, 1);
          border: none;
          width: 160px;
          height: 50px;
          &:hover {
            background: #ff7f5b;
          }
        }
        &.pages-btn-bl {
          .el-button {
            background: #333333;
            color: #fff;
            &:hover {
              background: #444444;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.pay-wrapper {
  width: 100%;
  height: 100%;
  background: #fff;
  overflow: auto;
  .pay-content {
    min-width: 1200px;
    margin: 50px 10%;
  }
  .count-down {
    font-size: 14px;
    color: #ff7f5b;
    margin-top: 50px;
  }
  .content-wrapper {
    margin-top: 50px;
  }
  .operation-wrapper {
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;
    height: 53px;
    text-align: right;
    border-bottom: 1px solid #ebf0f2;
    font-size: 14px;
    color: #999;
    > span {
      margin-right: 50px;
      padding-bottom: 10px;
      .count {
        color: #ff7f5b;
        font-weight: bold;
        &.price {
          font-size: 20px;
        }
      }
    }
    .el-button {
      margin-bottom: 7px;
    }
  }
  .read-box {
    text-align: right;
    margin-top: 10px;
    color: #999;
    font-size: 14px;
    .read-span {
      color: #333;
      cursor: pointer;
    }
  }
}
.info-img {
  img {
    width: 72px;
    height: 72px;
  }
}
.info-wrapper {
  .text {
  }
}
</style>
